package iotAPI

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisService"
	"gitee.com/fierce_wolf/go-fox-edge-common/commSql"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/FileName"
	_ "github.com/go-sql-driver/mysql" //具体使用的时候，请在服务中，某个go文件中import这一句话
	_ "github.com/mattn/go-sqlite3"    //具体使用的时候，请在服务中，某个go文件中import这一句话
	"io/ioutil"
	"strings"
)

type iotDefaultEntityManager struct {
}

func (e *iotDefaultEntityManager) Instance() {
	consumer := commRedisService.IRedisManager.GetRedisConsumer()
	consumer[commEntity.Type.ConfigEntity.Type()] = nil
}

func (e *iotDefaultEntityManager) InitLoadEntity() {
	// 初始化MYSQL/SQLite的数据库连接
	e.initDBConnect()

	commEntityManager.InitLoadEntity()
}

func (e *iotDefaultEntityManager) initDBConnect() {
	// 连接MYSQL数据库
	if commSql.GetDBType() == "mysql" {
		err := commSql.Client.ConnectMySQL()
		if err != nil {
			panic("连接数据库失败:" + err.Error())
		}
		return
	}

	// 连接SQLite3数据库
	if commSql.GetDBType() == "sqlite3" {
		// 打开数据库
		err := commSql.Client.ConnectSQLite("fox-edge.db")
		if err != nil {
			panic("连接数据库失败:" + err.Error())
		}

		// 读取初始化脚本的内容
		filePath := FileName.GetOsFilePath(commEnv.Service.WorkDir + "/sql/init_sqlite3.sql")
		ctx, err := ioutil.ReadFile(filePath)
		if err != nil {
			return
		}

		// 根据分号分拆SQL语句
		sqls := strings.Split(string(ctx), ";")

		// 逐个执行sql语句
		for _, sql := range sqls {
			commSql.Client.Exec(sql+";", nil)
		}

		return
	}
}
